﻿namespace IntegrationTests.QueryCorrectnessTests
{
    using System;
    using System.Collections.Generic;
    using System.DirectoryServices.Protocols;

    using DirectoryServicesProtocolsExtensions.SearchRequest;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class QueryPreExecutionTests : DirectoryTest
    {
        [TestInitialize]
        public void InitTests()
        {
            TestInitialize();
        }

        [TestMethod, Description("Would throw exception if fails")]
        public void IsBaseDNAccessiblePositiveTest()
        {
            var pagedSearchRequest = new PagedSearchRequest(LdapSearchRequestPropertiesContainer);
            pagedSearchRequest.TestConnectionToBaseDN(LdapConnectionFactory.Create());
        }

        [TestMethod]
        [ExpectedException(typeof(DirectoryOperationException))]
        public void IsBaseDNAccessibleNegativeTest()
        {
            LdapSearchRequestPropertiesContainer.SearchBaseDN = "CN=IdontExist,CN=Users,DC=fabrikam,DC=com";
            var pagedSearchRequest = new PagedSearchRequest(LdapSearchRequestPropertiesContainer);
            pagedSearchRequest.TestConnectionToBaseDN(LdapConnectionFactory.Create());
        }

        [TestMethod]
        public void AreAttributesToGetDefinedInSchemaPositiveTest()
        {
            var pagedSearchRequest = new PagedSearchRequest(LdapSearchRequestPropertiesContainer);
            List<string> undefinedAttributes;
            pagedSearchRequest.AreSuppliedAttributesDefinedInSchema(
                    LdapConnectionFactory.Create(), LdapMetaMapFactory, out undefinedAttributes);
            Assert.IsTrue(undefinedAttributes.Count == 0);
        }

        [TestMethod]
        public void AreAttributesToGetDefinedInSchemaNegativeTest()
        {
            var attributesToLoad = LdapSearchRequestPropertiesContainer.AttributesToLoad;
            Array.Resize(ref attributesToLoad, attributesToLoad.Length + 1);
            attributesToLoad[attributesToLoad.Length - 1] = "IDoNotExist";

            var pagedSearchRequest = new PagedSearchRequest(LdapSearchRequestPropertiesContainer);
            try
            {
                List<string> undefinedAttributes;
                pagedSearchRequest.AreSuppliedAttributesDefinedInSchema(
                    LdapConnectionFactory.Create(), LdapMetaMapFactory, out undefinedAttributes);
            }
            catch (Exception e)
            {
                Assert.IsTrue(e.Message.StartsWith(
                    "Some attributesToLoad specified in the query could not be found in the Active Directory Schema"));
            }
        }
    }
}
